<template>
  <div class="pdf_wrapper">
    <!-- PDF 渲染容器 -->
    <div ref="pdfContainer" class="pdf_container">
      <slot></slot>
    </div>
  </div>
</template>

<script>
import * as pdfjsLib from "pdfjs-dist/build/pdf";
import "pdfjs-dist/build/pdf.worker.entry";
import { getSignTemplateFile } from "@/api/signManage/petition.js";
export default {
  props: {
    templateId: {
      type: [String, Number],
      default: 56,
    },
  },
  mounted() {
    // this.loadDataFromServer();
  },
  methods: {
    async loadDataFromServer(id = this.templateId) {
      const data = await getSignTemplateFile(id);
      const arrayBuffer = await data.arrayBuffer();
      const typedArray = new Uint8Array(arrayBuffer);
      try {
        const loadingTask = pdfjsLib.getDocument({ data: typedArray });
        const pdfObj = await loadingTask.promise;
        this.renderAllPages(pdfObj);
      } catch (err) {
        console.error("PDF 加载失败:", err);
      }
    },
    async renderAllPages(pdf) {
      const container = this.$refs.pdfContainer;
      container.innerHTML = ""; // 清空

      // 加载 PDF

      for (let i = 1; i <= pdf.numPages; i++) {
        const page = await pdf.getPage(i);
        const viewport = page.getViewport({ scale: 1.5 });

        const canvas = document.createElement("canvas");
        const context = canvas.getContext("2d");
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        canvas.style.display = "block";
        canvas.style.marginBottom = "10px";

        container.appendChild(canvas);

        const renderContext = {
          canvasContext: context,
          viewport: viewport,
        };

        await page.render(renderContext).promise;
      }
    },
  },
};
</script>

<style scoped>
.pdf_wrapper {
  position: relative;
  border: 2px solid rgb(208, 207, 207);
  overflow-y: auto;
  /* 滚动条样式（Chrome、Edge、Safari） */
  &::-webkit-scrollbar {
    width: 8px; /* 滚动条宽度 */
  }
  &::-webkit-scrollbar-track {
    background: #f0f0f0; /* 滚动条轨道颜色 */
    border-radius: 4px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1; /* 滚动条滑块颜色 */
    border-radius: 4px;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #a0a0a0; /* 滑块 hover 颜色 */
  }

  /* Firefox 滚动条样式 */
  scrollbar-width: thin; /* 瘦滚动条 */
  scrollbar-color: #c1c1c1 #f0f0f0; /* 滑块颜色 轨道颜色 */
}

.pdf_container {
  display: block;
}
</style>
